<template>
  <el-card>
    <el-row align="middle">
      <el-col :span="12">
        <el-button :plain="type===2" :type="type===1?'primary':'info'" @click="loadPage(1)">项目描述</el-button>
        <el-button :plain="type===1" :type="type===1?'info':'primary'" @click="loadPage(2)">逐字稿</el-button>
      </el-col>
      <el-col :span="12">
        <el-row justify="end" align="middle">
          已提交{{ status.done }}位同学
          <el-button class="danger" type="text" @click="isShowYet = true">未提交{{ status.yet }}位同学</el-button>
          <el-button type="primary" @click="isShowImport = true">导入数组</el-button>
          <el-button type="primary" @click="isShowAdd = true">添加学生</el-button>
          <el-button type="primary" @click="exportExecl">导出评论</el-button>
        </el-row>
      </el-col>
    </el-row>
  </el-card>

  <el-card>
    <el-table :data="studentList" @row-click="rowClick" ref="studentTable">
      <el-table-column type="expand">
        <template v-slot="{row:{homework}}">
          <HomeworkTable :homework="homework" @showMdDialog="showMdDialog" @showNotMdDialog="showNotMdDialog" />
        </template>
      </el-table-column>
      <el-table-column label="姓名" prop="name"></el-table-column>
      <el-table-column label="已提交次数">
        <template v-slot="{ row }">
          <el-button type="text" :class="{ danger: row.homework.length === 0 }">{{ row.homework.length }} 份</el-button>
        </template>
      </el-table-column>
      <el-table-column label="待批改文件">
        <template v-slot="{ row }">
        <el-row>
          <el-button class="fileItem" :class="{danger: /.md$/.test(item.originName)}" type="text" @click.stop="showMdDialog(item._id)" v-for="(item, index) in row.homework.filter(i=>!i.level)" :key="index">
            {{item.originName}}
          </el-button>
        </el-row>
        </template>
      </el-table-column>
    </el-table>
  </el-card>

  <el-dialog v-model="isShowAdd" title="添加学生" @close="clearForm">
    <el-form>
      <el-form-item label="班级">
        <el-select v-model="formData.class" filterable placeholder="Select">
          <el-option v-for="item in classes" :key="item._id" :label="item.name" :value="item._id" />
        </el-select>
      </el-form-item>
      <el-form-item label="姓名">
        <el-input v-model="formData.name"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitAdd" type="primary">提交</el-button>
    </template>
  </el-dialog>

  <el-dialog v-model="isShowImport" title="导入学生" @close="clearImport">
    <el-form>
      <el-form-item label="班级">
        <el-select v-model="importClass" filterable placeholder="Select">
          <el-option v-for="item in classes" :key="item._id" :label="item.name" :value="item._id" />
        </el-select>
      </el-form-item>
      <el-form-item label="姓名数组">
        <el-input type="textarea" v-model="studentArrStr"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitImport" type="primary">提交</el-button>
    </template>
  </el-dialog>

  <el-dialog v-model="isShowYet" title="暂未提交">
    <div class="yetList">
      <span class="yetItem" v-for="student in yet" :key="student._id">{{ student.name }}</span>
    </div>
  </el-dialog>

  <el-dialog @close="clearMdData" fullscreen v-model="isShowMdDialog" title="批改 markdown">
    <el-row :gutter="28">
      <el-col :span="18" class="mdWrapper">
        <Markdown :source="mdSource" />
      </el-col>
      <el-col :span="6">
        <h3>等级</h3>
        <el-select v-model="mdLevel">
          <el-option
          v-for="item in ['A','B','C','D']"
          :key="item"
          :value="item"
        />
        </el-select>
        <h3>评论</h3>
        <el-input
          v-model="mdComment"
          :rows="14"
          type="textarea"
          placeholder="Please input"
        />
      </el-col>
    </el-row>
    <template #footer>
      <el-button type="primary" @click="submitComment">确定</el-button>
      <el-button type="danger" @click="isShowMdDialog = false">取消</el-button>
    </template>
  </el-dialog>

  <el-dialog @close="clearNotMdData" v-model="isShowNotMdDialog" title="批改其他格式">
    <h3>等级</h3>
    <el-select v-model="notMdLevel">
      <el-option
      v-for="item in ['A','B','C','D']"
      :key="item"
      :value="item"
    />
    </el-select>
    <h3>评论</h3>
    <el-input
      v-model="notMdComment"
      :rows="10"
      type="textarea"
      placeholder="Please input"
    />
    <template #footer>
      <el-button type="primary" @click="submitNotMdComment">确定</el-button>
      <el-button type="danger" @click="isShowNotMdDialog = false">取消</el-button>
    </template>
  </el-dialog>
</template>
<script setup>
import { getStudents, addStudent } from '@/api/students'
import { getClasses } from '@/api/classes'
import { getMd, getHomework, updateHomework } from '@/api/homeworks'
import { computed, onMounted, reactive, ref } from 'vue'
import HomeworkTable from './components/HomeworkTable.vue'
import Markdown from 'vue3-markdown-it'
import { ElMessage } from 'element-plus'

const isShowMdDialog = ref(false)
const mdSource = ref('')
const mdId = ref('')
const mdComment = ref('')
const mdLevel = ref('')

const type = ref(2)

const isShowNotMdDialog = ref(false)
const notMdId = ref('')
const notMdComment = ref('')
const notMdLevel = ref('')

const studentList = ref([])
const classes = ref([])
const isShowAdd = ref(false)
const isShowImport = ref(false)
const isShowYet = ref(false)
const studentArrStr = ref('')
const importClass = ref('')
const studentTable = ref()
const status = reactive({
  done: 0,
  yet: 0
})
const formData = reactive({
  name: '',
  class: ''
})

const loadPage = async(newType) => {
  if (newType) {
    type.value = newType
  }

  studentList.value = (await getStudents()).map(s => {
    return {
      ...s,
      homework: s.homework.filter(h => +h.type === +type.value)
    }
  })
  classes.value = await getClasses()

  status.done = studentList.value.filter(item => item.homework.length !== 0).length
  status.yet = studentList.value.length - status.done
}
const clearForm = () => {
  formData.name = ''
  formData.class = ''
}
const clearImport = () => {
  importClass.value = ''
  studentArrStr.value = ''
}
const submitAdd = async() => {
  await addStudent(formData)
  studentList.value = await getStudents()
  isShowAdd.value = false
}
const submitImport = async() => {
  try {
    const arr = JSON.parse(studentArrStr.value)
    await addStudent(arr.map(name => {
      return {
        name,
        class: importClass.value
      }
    }))
    studentList.value = await getStudents()
    isShowImport.value = false
  } catch (error) {
    console.log(error)
  }
}

const yet = computed(() => {
  return studentList.value.filter(i => i.homework.length === 0)
})
const rowClick = row => {
  studentList.value.forEach(element => {
    if (element._id !== row._id) {
      studentTable.value.toggleRowExpansion(element, false)
    } else {
      studentTable.value.toggleRowExpansion(element)
    }
  })
}
const showMdDialog = async id => {
  const homework = await getHomework(id)
  if (!/.md$/.test(homework.originName)) {
    ElMessage.error('非 md 文件请下载后点评')
    const row = studentList.value.find(i => i._id === homework.student)
    studentList.value.forEach(element => {
      if (element._id !== row._id) {
        studentTable.value.toggleRowExpansion(element, false)
      } else {
        studentTable.value.toggleRowExpansion(element, true)
      }
    })
    return
  }
  mdId.value = homework._id
  mdComment.value = homework.comment
  mdLevel.value = homework.level
  mdSource.value = await getMd(homework.path)
  isShowMdDialog.value = true
}
const submitComment = async() => {
  await updateHomework({
    id: mdId.value,
    level: mdLevel.value,
    comment: mdComment.value
  })
  ElMessage.success('修改成功')
  isShowMdDialog.value = false

  // TODO 用来处理待批改数量的, 有没有办法不需要整页刷新? 或者如果整页刷新, 点击编辑就不需要再次获取作业了吧?
  loadPage()
}
const showNotMdDialog = async id => {
  const homework = await getHomework(id)
  notMdId.value = homework._id
  notMdComment.value = homework.comment
  notMdLevel.value = homework.level
  isShowNotMdDialog.value = true
}
const submitNotMdComment = async() => {
  await updateHomework({
    id: notMdId.value,
    level: notMdLevel.value,
    comment: notMdComment.value
  })
  ElMessage.success('修改成功')
  isShowNotMdDialog.value = false

  // TODO 用来处理待批改数量的, 有没有办法不需要整页刷新? 或者如果整页刷新, 点击编辑就不需要再次获取作业了吧?
  loadPage()
}
const clearMdData = () => {
  mdId.value = ''
  mdComment.value = ''
  mdLevel.value = ''
  mdSource.value = ''
}
const clearNotMdData = () => {
  notMdId.value = ''
  notMdComment.value = ''
  notMdLevel.value = ''
}

const exportExecl = async() => {
  const { export_json_to_excel } = await import('@/utils/Export2Excel')
  const header = ['姓名', '评级', '作业文件', '评论']
  const data = []
  studentList.value.forEach(student => {
    student.homework.forEach(homework => {
      data.push([student.name, homework.level, homework.originName, homework.comment])
    })
  })
  export_json_to_excel({
    filename: '项目描述点评',
    header,
    data
  })
}

onMounted(async() => {
  loadPage()
})
</script>
<style scoped lang="scss">
.danger {
  color: red;
}
.yetList {
  display: flex;
  flex-wrap: wrap;
}
.yetItem {
  margin: 2px 8px;
  border: 1px solid #faa;
  padding: 4px;
  width: 20%;
  font-size: 18px;
  box-sizing: border-box;
  text-align: center;
}
.innerTableWrapper {
  padding: 10px 60px;
}
.fileItem {
  margin: 0 12px;
}
.mdWrapper {
  height: calc(100vh - 200px);
  overflow: auto;
}
</style>
